<?php

/**
 * Created by PhpStorm.
 * User: sqqq
 * Date: 2018/08/22
 * Time: 10:18
 */
class ApiEvaluationController extends BaseController
{
    /**
     * @Author:      sqq
     * @DateTime:   2018-08-22 10:19:29
     * @Description: 评价
     * @Param: $token String 用户token
     * @Param: $order_id String 订单号
     * @Param: $star Int 星级
     * @link:
     */
    public function evaluation(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'star' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()){
                $response = Lang::get('error.args_error_10000');
                $response['result'] = $validator->messages()->all();
                break;
            }
            $wechat_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wechat_user)){
                break;
            }
            try{
                DB::beginTransaction();

                //判断是否已评价
                $res = OrderEvaluation::where('order_id',Input::get('order_id'))->first();
                if(!is_null($res)){
                    return json_encode(array('code' => 1000310, 'msg' => '当前订单已评价'));
                }

                $orders = Orders::where('order_id',Input::get('order_id'))->where('user_id',$wechat_user->id)->first();
                if(is_null($orders)){
                    return $response = json_encode(array('code' => 1000311, 'msg' => '订单不存在'));
                }
                if(!is_null($orders) && !in_array($orders->status,[1117,1217,1317,1417])){
                    return $response = json_encode(array('code' => 1000312, 'msg' => '该订单不能评价'));
                }

                Orders::where('order_id',Input::get('order_id'))->where('user_id',$wechat_user->id)->update(['status' => 1018]);
                $evaluation = new OrderEvaluation();
                $evaluation->order_id = Input::get('order_id');
                $evaluation->eval_content = Input::get('content','');
                $evaluation->star = Input::get('star');
                $evaluation->save();

                $reason = "";
                $reason = Input::get('reason');
                if($reason){
                    $arr_id = explode(',',rtrim($reason,','));
                    if(count($arr_id)){
                        foreach($arr_id as $_a){
                            $ons = new OrderNotSatisfied();
                            $ons->order_id = Input::get('order_id');
                            $ons->reason = $_a;
                            $ons->save();
                        }
                    }
                }

                if(mb_strlen(Input::get('content','')) >= 10){
                    $activity = Coupons::getNewUserRegister(Config::get('config.evaluation_activity_id'),$response);
                    if(!is_null($activity)){
                        foreach ($activity as  $v) {
                            $coupon_base_info = Coupons::getCouponBaseInfo($v->coupon_base_info_id);
                            if (!$coupon_base_info) {
                                break;
                            }
                            if ($coupon_base_info->status == 0) {
                                break;
                            }
                            if ($coupon_base_info->date_type == 0 && strtotime($coupon_base_info->end_date.' 23:59:59') < strtotime(date('Y-m-d H:i', time()))) { //起止时间
                                break;
                            }
                            $coupon_whether_exist = Coupons::getCouponOther($v->coupon_base_info_id);
                            if (!is_null($coupon_whether_exist)) {
                                try{
                                    $coupons = Coupons::find($coupon_whether_exist->id);
                                    $coupons->status = 2;
                                    $coupons->received_user_id = $wechat_user->id;
                                    $coupons->get_time = date("Y-m-d H:i:s", time());
                                    if ($coupon_base_info->date_type == 1) { //顺延日期
                                        $coupons->end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                                    }
                                    $coupons->save();
                                    DB::commit();
                                    //return json_encode(array('code' => 1, "msg" => "已领取优惠券"));
                                    $response = array(
                                        'code' => 1,
                                        'msg' => '已领取优惠券',
                                    );
                                }catch (Exception $e){
                                    $response = array(
                                        'code' => 0,
                                        'msg' => 'ok',
                                    );
                                }
                            }else{
                                $response = array(
                                    'code' => 0,
                                    'msg' => 'ok',
                                );
                            }
                        }
                    }else{
                        $response = array(
                            'code' => 0,
                            'msg' => 'ok',
                        );
                    }
                }else{
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                    );
                }
                DB::commit();

                try{
                    if(Input::get('star') != 5){
                        DB::beginTransaction();

                        //数据处理
                        //获取会员等级
                        $member = MemberOrdinary::where('id',$wechat_user->member)->first();
                        if(is_null($member)){
                            $member_name = '普通会员';
                        }else{
                            $member_name = $member->name;
                        }

                        //查询车牌号、客户电话和订单金额
                        $orders = Orders::where('order_id',Input::get('order_id'))->first();
                        if(!is_null($orders)){
                            $phone = $orders->phone;
                            $car_no = $orders->car_no;
                            $payable_amount = $orders->payable_amount;
                            $order_status = $orders->order_type == 1 ? '服务单' : '零售单';
                            $name = $orders->name;
                        }else{
                            $phone = '';
                            $car_no = '';
                            $payable_amount = '';
                            $order_status = '';
                            $name = '';
                        }

                        $star = Input::get('star');
                        $eval_content = Input::get('content','');
                        $lable_str = '服务';
                        $desc = [
                            'content' => Input::get('content',''),
                            'type' => '评价',
                            'lable_str' => $lable_str,
                            'user_phone' => $wechat_user->phone,  //发布人手机号
                            'user_id' => $wechat_user->id,   //发布人id
                            'user_member' => $member_name,
                            'order_id' => Input::get('order_id'),
                            'phone' => $phone,  //送修人电话
                            'name' => $name,  //送修人手机号
                            'car_no' => $car_no,
                            'price' => $payable_amount,
                            'star' => $star,
                            'eval_content' => $eval_content,
                            'order_status' => $order_status,
                        ];
                        $desc = json_encode($desc);

                        //保存到数据库
                        $sc_notice = new ScNotice();
                        $sc_notice->activity_base_id = $evaluation->id;
                        $sc_notice->name = '[' . Input::get('order_id') . ']' .$eval_content;
                        $sc_notice->status = 1;
                        $sc_notice->desc = $desc;
                        $sc_notice->notice_type = 4;
                        $sc_notice->lable_str = $lable_str;
                        $sc_notice->created_type = 3;
                        $sc_notice->created_by = $wechat_user->id;
                        $sc_notice->created_at = Common::currentTimeString();
                        $sc_notice->updated_at = Common::currentTimeString();
                        $sc_notice->save();

                        $sc_notice_shop = new ScNoticeShop();
                        $sc_notice_shop->notice_id = $sc_notice->id;
                        $sc_notice_shop->activity_base_id = $evaluation->id;
                        $sc_notice_shop->shop_id = $orders->shop_id;
                        $sc_notice_shop->status = 1;
                        $sc_notice_shop->created_by = $wechat_user->id;
                        $sc_notice_shop->created_at = Common::currentTimeString();
                        $sc_notice_shop->updated_at = Common::currentTimeString();
                        $sc_notice_shop->save();

                        DB::commit();
                    }
                }catch(Exception $e){
                    DB::rollBack();
                    Log::error("error", array("system" => "api3.0" ,"event" => "evaluation", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get('error.data_save_error_30001');
                    break;
                }

            }catch (Exception $e){
                DB::rollBack();
                Log::error("error", array("system" => "api3.0" ,"event" => "evaluation", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get('error.data_save_error_30001');
                break;
            }
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "evaluation", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}